package com.bng8.superstar_cms.controller;

import com.bng8.superstar_cms.domain.common.PageQuery;
import com.bng8.superstar_cms.domain.common.PageResult;
import com.bng8.superstar_cms.domain.common.ResponseResult;
import com.bng8.superstar_cms.domain.dto.SupUserDTO;
import com.bng8.superstar_cms.domain.dto.SupUserQueryDTO;
import com.bng8.superstar_cms.domain.vo.SupUserVO;
import com.bng8.superstar_cms.exception.BusinessException;
import com.bng8.superstar_cms.exception.ErrorCodeEnum;
import com.bng8.superstar_cms.service.SupUserService;
import com.bng8.superstar_cms.util.InsertValidationGroup;
import com.bng8.superstar_cms.util.UpdateValidationGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * ClassName: AdminController
 * Package: com.bng8.superstar_cms.controller
 * Date: 2023/8/15 11:03
 * Author: 安知（13921877634）
 */
@Slf4j
@Validated
@RestControllerAdvice
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private SupUserService supUserService;

    /**
     * 新增用户信息
     * @param supUserDTO 前端传入用户信息
     * @return 返回值
     */
    @PostMapping
    @CacheEvict(cacheNames = "users-cache", allEntries = true)
    public ResponseResult insertUser(HttpServletRequest request,
                                     @RequestBody @Validated(InsertValidationGroup.class) SupUserDTO supUserDTO) {
        int save = 0;
        try {
            save = supUserService.save(supUserDTO, request);
        } catch (Exception e) {
            log.error("用户新增失败", e);
            throw new BusinessException(
                    ErrorCodeEnum.INSERT_FAILURE, e);
        }
        if (1 == save) {
            return ResponseResult.success("新增成功");
        } else {
            return ResponseResult.failure(ErrorCodeEnum.INSERT_REPEAT_FAILURE);
        }
    }

    /**
     * 更新用户信息
     *
     * @param id         用户id
     * @param supUserDTO 前端传入用户信息
     * @return 返回值
     */
    @PutMapping("/{id}")
    @CacheEvict(cacheNames = "users-cache", allEntries = true)
    public ResponseResult updateUser(HttpServletRequest request,
                                     @NotNull @PathVariable("id") Long id,
                                     @Validated(UpdateValidationGroup.class) @RequestBody SupUserDTO supUserDTO) {
        int update = supUserService.update(id, supUserDTO, request);
        if (update == 1) {
            return ResponseResult.success("更新成功！");
        } else {
            return ResponseResult.failure(ErrorCodeEnum.UPDATE_FAILURE);
        }
    }

    /**
     * 删除用户信息
     * @param id 用户id
     * @return 返回值
     */
    @DeleteMapping("/{id}")
    @CacheEvict(cacheNames = "users-cache", allEntries = true)
    public ResponseResult deleteUser(@NotNull(message = "用户ID不能为空!") @PathVariable("id") Long id) {
        boolean removed = supUserService.removeById(id);
        if (removed) {
            return ResponseResult.success("删除成功！");
        } else {
            return ResponseResult.failure(ErrorCodeEnum.DELETE_FAILURE);
        }
    }

    /**
     * 分页查询用户信息
     *
     * @param pageNo
     * @param pageSize
     * @param query
     * @return
     */
    @GetMapping
    @Cacheable(cacheNames = "users-cache")
    public ResponseResult<PageResult> query(@NotNull Integer pageNo, @NotNull Integer pageSize,
                                            @Validated SupUserQueryDTO query) {

        // 构造查询条件
        PageQuery<SupUserQueryDTO> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        pageQuery.setQuery(query);

        // 查询
        PageResult<List<SupUserDTO>> pageResult =
                supUserService.query(pageQuery);

        // 实体转换
        List<SupUserVO> userVOList = Optional
                .ofNullable(pageResult.getData())
                .map(List::stream)
                .orElseGet(Stream::empty)
                .map(supUserDTO -> {
                    SupUserVO supUserVO = new SupUserVO();
                    BeanUtils.copyProperties(supUserDTO, supUserVO);
                    // 对特殊字段做处理
                    supUserVO.setPassword("******");
                    supUserVO.setChallenger(supUserDTO.getChallenger().getChallenger());
                    return supUserVO;
                })
                .collect(Collectors.toList());

        // 封装返回结果
        PageResult<List<SupUserVO>> result = new PageResult<>();
        BeanUtils.copyProperties(pageResult, result);
        result.setData(userVOList);

        return ResponseResult.success(result);
    }
}